import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import {Button, Form, Row, Col, Card, Spin, Modal} from 'antd';
import TextInput from 'Shared/components/TextInput';
import {FORM_OPTIONS} from '../constants';
import Return from '../common/Return';
import FormItem from 'antd/lib/form/FormItem';
import {hasPermissions} from './utils';
import {PERMISSIONS} from './constants';
import {newOrUpdateOrderValidator} from './validator';
import {injectIntl, language} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import DealerTable from './DealerTable';
import DealerTree from './DealerTree';
import WrappedDatePicker from '../common/WrappedDatePicker';
import DateRangePicker from 'Shared/components/DateRangePicker';
import styles from './style.css';
import {lcKind, currency, isBatchesStatus} from '../Enum';
import {getDealersQuickly, getDealers} from './api';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
const YesNo = isBatchesStatus.toList(language);
const lcKindOptions = lcKind.toList(language);
const currencyOptions = currency.toList(language);
const EMPTY_ARRAY = [];

export class RegisterPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        data: {},
        showDealerSelectPanel: false,
    };

    componentDidMount() {
        this.ismounted = true;
    }
    
    componentWillUnmount() {
        this.ismounted = false;
    }

    
    handleFilterChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }

    
    dealerLabelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `(${d.code}) ${d.name}`;
        return '';
    }

    onClickReturnBtn = () => {
        this.props.onCancel();
    }

    onSearchDealer = value =>
        getDealersQuickly({filter: value})
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            })
            
    onSelectDealer = dealer => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                dealerId: dealer.id,
                dealerCode: dealer.code,
                dealerName: dealer.name,
            })
        });
    }

    onSearchDealer = value =>
        getDealersQuickly({filter: value})
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            })

    onClickSearchDealerBtn = () => {
        this.setState({showDealerSelectPanel: true});
    }

    onCloseDealerSelectPanel= () => {
        this.setState({showDealerSelectPanel: false});
    }

    onChangeSwitchBrand = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value,
            brandCode: this.props.brands.find(v => v.value === value).text,
            dealerId: '',
            dealerCode: '',
            dealerName: '',

        });
        this.setState({
            data,
            hasOperat: true
        });
    }

    onChangeBrand = (value, name) => {
        if(this.state.data.brandId !== undefined && this.state.data.brandId !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch2',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch',
                    defaultMessage: '变更品牌，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onChangeSwitchBrand(value, name)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value,
                    brandCode: this.props.brands.find(v => v.value === value).text
                }),
                hasOperat: true
            });
    }

    onSubmit = () => {
        const isValid = newOrUpdateOrderValidator(this.state.data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        this.props.onSubmit(this.state.data).then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    }

    render() {
        const data = this.state.data;
        const validateBrand = !data.brandId && this.state.validate ? 'error' : null;
        const validateDealer = !data.dealerId && this.state.validate ? 'error' : null;
        const validateCode = !data.code && this.state.validate ? 'error' : null;
        const validateIssueCountry = !data.issueCountry && this.state.validate ? 'error' : null;
        const validateIssueBank = !data.issueBank && this.state.validate ? 'error' : null;
        const validateLcPayMentDays = !data.lcPayMentDays && this.state.validate ? 'error' : null;
        const validateIssuePrice = !data.issuePrice && this.state.validate ? 'error' : null;
        const validateIssueDate = !data.issueDate && this.state.validate ? 'error' : null;
        const validateLcKind = !data.lcKind && this.state.validate ? 'error' : null;
        const validateCurrency = !data.currency && this.state.validate ? 'error' : null;
        const validateLastLoadDate = !data.lastLoadDate && this.state.validate ? 'error' : null;
        const validateValidityDate = !data.validityDate && this.state.validate ? 'error' : null;
        const validateIsBatches = !data.isBatches && this.state.validate ? 'error' : null;
        const {formatMessage} = this.props.intl;
        const {pagePermission} = this.props;
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName,
        } : null;
        if(this.props.brands.length === 1 && !this.props.id)
            data.brandId = this.props.brands[0].value;
        const submitable = hasPermissions(PERMISSIONS.register, pagePermission);
        
        const queryCondition = {
            brandId: data.brandId
        };
        const dealerComp = data.brandId ? (<DealerSelectPanel
            allowClear={false}
            value={dealerInfo}
            getDealerSimple={getDealersQuickly}
            getDealers={getDealers}
            conditions={queryCondition}
            onSelect={this.onSelectDealer} />) : (<TextInput name="dealerId"
            value={''} disabled placeholder={this.props.intl.formatMessage({
                id: 'newPanel.dealerComp.placeholder',
                defaultMessage: '请先选择品牌'
            })} />);
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card {...FORM_OPTIONS.col} title={formatMessage({
                            id: 'registerPanel.card.title',
                            defaultMessage: '信用证信息编辑'
                        })}>
                            <Row>
                                {
                                    this.props.brands.length !== 1 &&
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'registerPanel.form.brand',
                                                defaultMessage: '品牌'
                                            })}
                                            {...FORM_OPTIONS.item} validateStatus={validateBrand} required >
                                            <WrappedSelect
                                                allowClear
                                                name="brandId"
                                                value={data.brandId}
                                                options={this.props.brands}
                                                onChange={this.onChangeBrand}/>
                                        </FormItem>
                                    </Col>
                                }
                                <Col {...FORM_OPTIONS.col}>
                                    {this.props.id || this.props.isDealerUser ? (
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'registerPanel.form.dealerId',
                                                defaultMessage: '总代'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <span className="value-font">({data.dealerCode}) {data.dealerName}</span>
                                        </FormItem>
                                    ) : (
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'registerPanel.form.dealerId',
                                                defaultMessage: '总代'
                                            })}
                                            {...FORM_OPTIONS.item}
                                            validateStatus={validateDealer}
                                            required>
                                            {dealerComp}
                                        </FormItem>
                                    )}
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'registerPanel.text.code',
                                        defaultMessage: '信用证号码'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateCode} required >
                                        <TextInput
                                            name="code"
                                            value={data.code}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'registerPanel.text.issueCountry',
                                        defaultMessage: '开证国家'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateIssueCountry} required >
                                        <TextInput
                                            name="issueCountry"
                                            value={data.issueCountry}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'registerPanel.text.issueBank',
                                        defaultMessage: '开证银行'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateIssueBank} required >
                                        <TextInput
                                            name="issueBank"
                                            value={data.issueBank}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'registerPanel.text.sendBank',
                                        defaultMessage: '寄出银行'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="sendBank"
                                            value={data.sendBank}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'registerPanel.text.lcPayMentDays',
                                        defaultMessage: '信用证账期'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateLcPayMentDays} required >
                                        <TextInput
                                            name="lcPayMentDays"
                                            value={data.lcPayMentDays}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'registerPanel.text.currency',
                                        defaultMessage: '币种'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateCurrency} required >
                                        <WrappedSelect
                                            id="currency"
                                            allowClear={true}
                                            value={data.currency}
                                            onChange={this.handleFilterChange}
                                            options={currencyOptions} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'registerPanel.text.issuePrice',
                                        defaultMessage: '开证金额'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateIssuePrice} required >
                                        <LocalizeInputNumber
                                            precision={2}
                                            name="issuePrice"
                                            value={data.issuePrice}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'registerPanel.text.issueDate',
                                        defaultMessage: '开证日期'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateIssueDate} required >
                                        <WrappedDatePicker
                                            name="issueDate"
                                            value={data.issueDate}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem className={styles.multiLabel} label={formatMessage({
                                        id: 'registerPanel.text.lastLoadDate',
                                        defaultMessage: '最迟装船日期'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateLastLoadDate} required >
                                        <WrappedDatePicker
                                            name="lastLoadDate"
                                            value={data.lastLoadDate}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'registerPanel.text.validityDate',
                                        defaultMessage: '有效期'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateValidityDate} required >
                                        <DateRangePicker
                                            id="validityDate"
                                            value={data.validityDate}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'registerPanel.text.lcKind',
                                        defaultMessage: '信用证类型'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateLcKind} required >
                                        <WrappedSelect
                                            id="lcKind"
                                            allowClear={true}
                                            value={data.lcKind}
                                            onChange={this.handleFilterChange}
                                            options={lcKindOptions} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'registerPanel.text.isBatches',
                                        defaultMessage: '是否分批'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateIsBatches} required >
                                        <WrappedSelect
                                            allowClear
                                            id="isBatches"
                                            options={YesNo}
                                            value={data.isBatches}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'registerPanel.text.amount',
                                        defaultMessage: '件数'
                                    })} {...FORM_OPTIONS.item}>
                                        <LocalizeInputNumber
                                            name="amount"
                                            min={0}
                                            value={data.amount}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
                <Modal
                    title={formatMessage({
                        id: 'dealer.dealers.modal.item.title',
                        defaultMessage: '总代子公司查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showDealerSelectPanel}
                    onCancel={this.onCloseDealerSelectPanel}>
                    <Row gutter={8}>
                        <Col md={8} xl={8} xxl={6}><DealerTree /></Col>
                        <Col md={16} xl={16} xxl={18}><Card>
                            <DealerTable onSelect={this.onSelectDealer} />
                        </Card></Col>
                    </Row>
                </Modal>
                <Card type="inner">
                    <Row>
                        <Col disabled={!submitable} className="col-align-right">
                            <Button key="submit" loading={this.state.loading}
                                onClick={this.onSubmit} type="primary">{formatMessage({
                                    id: 'registerPanel.btn.submit',
                                    defaultMessage: '保存'
                                })}</Button>
                        </Col>
                    </Row>
                </Card>
            </div>
        );
    }
}

RegisterPanel.propTypes = {
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    brands: PropTypes.array,
    conditions: PropTypes.object,
    history: PropTypes.object,
    pagePermission: PropTypes.array,
};
import {connect} from 'react-redux';
import {
    onSubmit,
    tableSearch,
    saveQueryCondition
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getBrands = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'brands']),
    data => {
        const brands = data.toJS();
        return brands
            ? brands.map(item => ({
                value: item.id,
                text: `(${item.code})${item.name}`
            }))
            : EMPTY_ARRAY;
    }
);

const mapStateToProps = state => ({
    conditions: getConditions(state),
    pagePermission: getPagePermission(state),
    brands: getBrands(state),
});

const mapDispatchToProps = (dispatch, props) => {
    const ownProps = {
        onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
        onSubmit: data => dispatch(onSubmit(data)).then(res => {
            if(res.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
            return res.success;
        }),
        onCancel: () => props.history.push(routes.query.url())
    };
    return ownProps;
};

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(RegisterPanel));
